﻿using DaZhong.app_code;
using DaZhong.Model;
using HtmlAgilityPack;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using QD.Sht.Common;
using QD.Utils;
using QD.WX.BLL;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Windows.Forms;
using WeiTap.Web;

namespace DaZhong
{
    /// <summary>
    ///  
    /// </summary>
    public partial class frmSougou : BaseForm
    {
        public frmDefault fdefalut;
        Thread thdOne = null;

        List<ids> lastIds = new List<ids>();//腾讯新闻-保存上一次访问的数据
        public frmSougou()
        {
            InitializeComponent();
        }
        public delegate string GetText();


        public static List<SendModel> listSendModel = new List<SendModel>();
        private void frmSheHui_Load(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tagname"></param>
        /// <param name="type">0：通过公众号，1：通过关键词,3:通过链接</param>
        /// <param name="url">链接</param>
        public void Do(string tagname, int type = 0,string url="")
        {
            thdOne = new Thread(() => ThreadDoing(tagname, type,url)) { IsBackground = true };
            thdOne.Start();
        }


        public void ThreadDoing(string tagname, int type,string url="")
        {
            this.textBox = textBox1;
            ThreadPool.QueueUserWorkItem(o => Work(tagname, o, type,url));
        }

        //循环等待时间
        protected void Work(string tagname, object stateInfo, int type,string url="")
        {
            try
            {
                var tagModel = WeiTap.Article.Dal.ArticelTagManager.GetTag(tagname).Result;
                if (tagModel == null)
                {
                    Echo("未找到相关的标签");
                }
                else
                {
                    var name = tagModel.Name;
                    if (type == 0)
                    {
                        var acs = tagModel.WtAccounts.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (var ac in acs)
                        {
                            var list = GetWeiChatAcountList(tagModel.Id, tagModel.Name, ac); //搜狗微信公众号列表
                            if (list.Count <= 0) continue;
                            Echo($"存储到数据库中...");
                            var msg = DAOArticle.Insert(list.Reverse().ToList());
                            Echo($"完成操作:{msg}...");
                        }
                        Echo("采集结束");
                    }
                    else if(type==1)
                    {
                        var keys = tagModel.KeyWords.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (var key in keys)
                        {
                            var list = GetWeiChatAcountListKey(tagModel.Id, tagModel.Name, key); //搜狗微信关键词列表
                            if (list.Count <= 0) continue;
                            Echo($"存储到数据库中...");
                            var msg = DAOArticle.Insert(list.Reverse().ToList());
                            Echo($"完成操作:{msg}...");
                        }
                        Echo("采集结束");
                    }
                    else if (type == 2)
                    {
                        if (string.IsNullOrEmpty(url))
                        {
                            Echo("请填写链接地址");
                        }
                        else
                        {
                            var list = new List<MArticle>();
                            var ma = SearchArticle(url, tagModel.Id, tagModel.Name);
                            if (DAOArticle.Exist(ma.title))
                            {
                                Echo($"[{ma.title}]文章标题已存在,放弃");
                                return;
                            }
                            list.Add(ma);
                            Echo($"存储到数据库中...");
                            var msg = DAOArticle.Insert(list);
                            Echo($"完成操作:{msg}...");
                        }
                        
                    }

                }
            }
            catch (Exception e)
            {
                Echo($"系统错误:{e.Message}");
                Trace.WriteLine(e.Message);
            }



        }

        /// <summary>
        /// 获取搜狗微信公众号，以及请求地址
        /// </summary>
        /// <param name="listSendModel"></param>
        /// <returns></returns>
        private IList<MArticle> GetWeiChatAcountList(int tagid, string tagname, string account)
        {
            var result = new List<MArticle>();
            Echo($"正在采集标签[{tagname}]-[{account}]");
            var searchUrl = string.Format(WebSiteUrls.WeiChat.WeiChatAccout, System.Web.HttpUtility.UrlEncode(account));
            var _accountUrl = GetWeiChatAccountUrl(searchUrl, account);
            if (!string.IsNullOrEmpty(_accountUrl))
            {
                var res = GetArticleList(_accountUrl, tagid, tagname,account).ToList();
                result.AddRange(res);
            }
            return result;
        }
        /// <summary>
        /// 获取搜狗微信关键词，以及请求地址
        /// </summary>
        /// <param name="listSendModel"></param>
        /// <returns></returns>
        private IList<MArticle> GetWeiChatAcountListKey(int tagid, string tagname, string key)
        {
            var result = new List<MArticle>();
            Echo($"正在采集标签[{tagname}]-关键词[{key}]");
            var res = GetArticleListKey(key, tagid, tagname).ToList();
            result.AddRange(res);

            return result;
        }
        /// <summary>
        /// 获取公众号详情页Url
        /// </summary>
        /// <param name="requestUrl"></param>
        /// <param name="accountCode"></param>
        /// <returns></returns>
        private string GetWeiChatAccountUrl(string requestUrl, string accountCode)
        {
            var href = "";
            //var www2 = new HttpFire("http://www.sogou.com") { Method = HttpRequestMethod.Get, AutoRedirect = true };
            //www2.GetString();
            //var sss = www2.Response.Cookies["SNUID"]?.Value;
            //var sssss = www2.Response.Cookies["SUV"]?.Value;
            var helper = new JietuDAL.DateHelp();
            var ds = helper.Select();
            var snuid = "";
            var suv = "";
            var www = new HttpFire(requestUrl) { Method = HttpRequestMethod.Get, AutoRedirect = true };
            www.Headers.AutoAddDefaultHeaders = true;
            www.Headers.Referer = "http://news.sogou.com/news?ie=utf8&p=40230447&query=KAMCHAFONG&";
            www.Headers.UserAgent =
                "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36";
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                snuid = ds.Tables[0].Rows[0][0].ToString();
                suv = ds.Tables[0].Rows[0][1].ToString();

                www.Cookies.Add(new Cookie("SNUID", snuid, "/", ".sogou.com"));
                www.Cookies.Add(new Cookie("SUV", suv, "/", ".sogou.com"));
            }



            Echo("正在请求网络数据");
            var htmlResult = www.GetString();
            if (htmlResult == null)
                return string.Empty;

            int reloadTimes = 3;//尝试三次输入验证码
            while (htmlResult.Contains("您的访问过于频繁") && reloadTimes > 0)
            {
                ds = helper.Select();
                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    snuid = ds.Tables[0].Rows[0][0].ToString();
                    suv = ds.Tables[0].Rows[0][1].ToString();
                    www.Cookies.Add(new Cookie("SNUID", snuid, "/", ".sogou.com"));
                    www.Cookies.Add(new Cookie("SUV", suv, "/", ".sogou.com"));

                }
                Echo($"搜索公众号出现验证码！SNUID:{snuid} SUV:{suv}");
                Process.Start("Chrome.exe", requestUrl);
                Echo($"请在30秒内输入验证码,您还有{reloadTimes}次机会");
                Thread.Sleep(30000);
                htmlResult = www.GetString();
                reloadTimes--;
            }
            if (htmlResult.Contains("您的访问过于频繁"))
            {
                Echo("您的访问过于频繁");
                return string.Empty;
            }
            var doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(htmlResult);
            var accountNode = doc.DocumentNode.SelectSingleNode("//*[@class=\"news-box\"]/ul/li[1]/div[1]/div[2]/p[2]/label[1]");
            var accountHref = doc.DocumentNode.SelectSingleNode("//*[@class=\"news-box\"]/ul/li[1]/div[1]/div[2]/p[1]/a[1]");
            var account = accountNode?.InnerText.Trim();
            href = accountHref?.Attributes["href"].Value;
            if (href == null) return string.Empty;
            if (account != null && !account.Equals(accountCode, StringComparison.OrdinalIgnoreCase))
            {
                Echo(string.Format("公众号不存在:{0}", accountCode)); return string.Empty;
            }

            return HttpUtility.HtmlDecode(href);
        }
        private IList<MArticle> GetArticleList(string requestUrl, int tagid, string tagname,string accountcode="")
        {
            IList<MArticle> result = new List<MArticle>();

            if (string.IsNullOrEmpty(requestUrl)) return result;
            try
            {
                WebRequestHelper.Referer = requestUrl;
                WebRequestHelper.Host = "mp.weixin.qq.com";
                var htmlResult = WebRequestHelper.Request(requestUrl);
                //var www = new HttpFire(requestUrl);
                //www.Path;
                //www.Method=HttpRequestMethod.Get;

                //var htmlResult = www.GetString();
                int reloadTimes = 3;//尝试三次输入验证码

                while (htmlResult.Contains("为了保护你的网络安全，请输入验证码") && reloadTimes > 0)
                {
                    var cert = DateTime.Now.Ticks.ToString() + new Random().NextDouble().ToString("0.0000");
                    var imgSrc = "http://mp.weixin.qq.com/mp/verifycode?cert=" + cert;
                    Echo(requestUrl);
                    Process.Start("Chrome.exe", requestUrl);
                    Echo($"请在30秒内输入验证码,您还有{reloadTimes}次机会");
                    Thread.Sleep(30000);
                    htmlResult = WebRequestHelper.Request(requestUrl);
                    reloadTimes--;
                }
                MArticle _article;
                Regex reg = new Regex("msgList = {([\\s\\S]+?)};");
                Match match = reg.Match(htmlResult);
                if (match.Success)
                {
                    var jsonString = match.Value.Substring(9).TrimEnd(';');
                    SougouWeiChatModel model = JsonConvert.DeserializeObject<SougouWeiChatModel>(jsonString);
                    if (model != null)
                    {

                        foreach (var item in model.list)
                        {
                            var htmlDate = new DateTime(1970, 1, 1).AddSeconds(item.comm_msg_info.datetime).ToString("yyyy-MM-dd HH:mm");
                            _article = new MArticle
                            {
                                Tag_Id = tagid,
                                Tag_Name = tagname,
                                sourceid = (int)EnumTypes.SourceIds.WeiChat
                            };
                            _article.source = EnumTypes.GetEnumDesc(typeof(EnumTypes.SourceIds), _article.sourceid);
                            _article.date = DateTime.Now.ToString();
                            _article.title = item.app_msg_ext_info.title;
                            _article.logo = ConfigurationManager.AppSettings["proxyimg"] + item.app_msg_ext_info.cover;
                            _article.htmlurl = item.app_msg_ext_info.content_url;
                            _article.htmlurl = "http://mp.weixin.qq.com" + WebRequestHelper.ReplaceHtml(_article.htmlurl);
                            _article.state = ((int)EnumTypes.ArticleStatus.nonChecked);//未审核
                            var copy = false;
                            _article.content = GetArticleContent(_article.htmlurl,out copy);
                            _article.html_date = htmlDate;
                            Echo($"正在采集：{_article.title}");
                            result.Add(_article);
                            foreach (var msg in item.app_msg_ext_info.multi_app_msg_item_list)
                            {
                                msg.title = HttpUtility.HtmlDecode(msg.title);
                                
                                if (DAOArticle.Exist(msg.title))
                                {
                                    Echo($"[{msg.title}]文章标题已存在,放弃");
                                    continue;
                                }
                                if (msg.copyright_stat == 11 || DAOArticle.Exist(msg.title))
                                {
                                    Echo($"[放弃-因为文章有版权限制]{msg.title}");
                                    continue;
                                }
                                _article = new MArticle
                                {
                                    Tag_Id = tagid,
                                    Tag_Name = tagname,
                                    sourceid = (int)EnumTypes.SourceIds.WeiChat
                                };
                                _article.source = EnumTypes.GetEnumDesc(typeof(EnumTypes.SourceIds), _article.sourceid)+"-"+accountcode;
                                _article.date = DateTime.Now.ToString();
                                _article.title = msg.title;
                                _article.logo = ConfigurationManager.AppSettings["proxyimg"] + msg.cover;
                                _article.htmlurl = msg.content_url;
                                _article.htmlurl = "http://mp.weixin.qq.com" + WebRequestHelper.ReplaceHtml(_article.htmlurl);
                                _article.state = ((int)EnumTypes.ArticleStatus.nonChecked);//未审核
                                var copyright = false;
                                _article.content = GetArticleContent(_article.htmlurl,out copyright);
                                _article.html_date = htmlDate;
                                Echo($"正在采集：{_article.title}");
                                var comm = GetComment(_article.htmlurl);
                                if (comm != null)
                                {
                                    _article.ReadNum = comm.read_num;
                                    _article.LikeNum = comm.like_num;
                                }
                                result.Add(_article);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Trace.TraceError(e.Message);
                throw;
            }
            return result;
        }
        private IList<MArticle> GetArticleListKey(string key, int tagid, string tagname, int page = 1)
        {
            var result = new List<MArticle>();
            try
            {
                var searchUrl = string.Format(WebSiteUrls.WeiChat.WeiChatKeyword, System.Web.HttpUtility.UrlEncode(key), page);
                var helper = new JietuDAL.DateHelp();
                var ds = helper.Select();
                var snuid = "";
                var suv = "";
                var www = new HttpFire(searchUrl) { Method = HttpRequestMethod.Get, AutoRedirect = true };
                www.Headers.AutoAddDefaultHeaders = true;
                www.Headers.Referer = "http://news.sogou.com/news?ie=utf8&p=40230447&query=KAMCHAFONG&";
                www.Headers.UserAgent =
                    "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36";
                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    snuid = ds.Tables[0].Rows[0][0].ToString();
                    suv = ds.Tables[0].Rows[0][1].ToString();

                    www.Cookies.Add(new Cookie("SNUID", snuid, "/", ".sogou.com"));
                    www.Cookies.Add(new Cookie("SUV", suv, "/", ".sogou.com"));
                }
                Echo($"正在请求第{page}页");
                var htmlResult = www.GetString();
                if (htmlResult == null)
                    return result;

                int reloadTimes = 3;//尝试三次输入验证码
                while (htmlResult.Contains("您的访问过于频繁") && reloadTimes > 0)
                {
                    ds = helper.Select();
                    if (ds != null && ds.Tables[0].Rows.Count > 0)
                    {
                        snuid = ds.Tables[0].Rows[0][0].ToString();
                        suv = ds.Tables[0].Rows[0][1].ToString();
                        www.Cookies.Add(new Cookie("SNUID", snuid, "/", ".sogou.com"));
                        www.Cookies.Add(new Cookie("SUV", suv, "/", ".sogou.com"));

                    }
                    Echo($"搜索公众号出现验证码！SNUID:{snuid} SUV:{suv}");
                    Process.Start("Chrome.exe", searchUrl);
                    Echo($"请在30秒内输入验证码,您还有{reloadTimes}次机会");
                    Thread.Sleep(30000);
                    htmlResult = www.GetString();
                    reloadTimes--;
                }
                if (htmlResult.Contains("您的访问过于频繁"))
                {
                    Echo("您的访问过于频繁");
                    return result;
                }
                var doc = new HtmlAgilityPack.HtmlDocument();
                doc.LoadHtml(htmlResult);
                var newlist = doc.QuerySelectorAll(".news-list ul li");
                foreach (var node in newlist)
                {
                    var a=new MArticle();
                    var link = node.QuerySelector(".txt-box h3 a");
                    if (link == null) continue;
                    a.htmlurl = HttpUtility.HtmlDecode(link.Attributes["href"]?.Value ?? "");
                    a.title = link.InnerText;
                    if (string.IsNullOrEmpty(a.title)) continue;
                    a.title = a.title.Replace("<!--red_beg-->", "")?.Replace("<!--red_end-->", "") ?? "";
                    a.title = HttpUtility.HtmlDecode(a.title);
                    if (DAOArticle.Exist(a.title))
                    {
                        Echo($"{a.title}文章标题已存在,放弃");
                        continue;
                    }
                    var img = node.QuerySelector(".img-box img");
                    Uri logoUri;
                    if (img != null)
                    {
                        var r = HttpUtility.HtmlDecode(img.Attributes["src"]?.Value ?? "");
                        Uri.TryCreate(r,UriKind.RelativeOrAbsolute, out logoUri);
                    }
                    else
                    {
                        var imgd = node.QuerySelectorAll(".txt-box .img-d img");
                        var r = HttpUtility.HtmlDecode(imgd?.FirstOrDefault()?.Attributes["src"]?.Value ?? "");
                        Uri.TryCreate(r,UriKind.RelativeOrAbsolute, out logoUri);
                    }
                    if (logoUri != null && logoUri.Host.Contains("sogoucdn"))
                    {
                        var query = logoUri.Query.TrimStart('?');
                        var rawUrl = query.Split('&').FirstOrDefault(t => t.StartsWith("url"))?.Split('=')[1];
                        a.logo = rawUrl;
                    }
                    else
                        a.logo = logoUri.ToString();
                    a.Tag_Id = tagid;
                    a.Tag_Name = tagname;
                    a.sourceid = (int) EnumTypes.SourceIds.WeiChat;
                    a.source = EnumTypes.GetEnumDesc(typeof(EnumTypes.SourceIds), a.sourceid);
                    
                    var p = node.QuerySelector(".s-p .s2 script");
                    var num2 = RegexFetch("([1-9]\\d*\\.?\\d*)|(0\\.\\d*[1-9])", p.InnerText);
                    long ticks = 0;
                    if (long.TryParse(num2, out ticks))
                    {
                        a.html_date = new DateTime(1970, 1, 1).AddSeconds(ticks).ToString();
                    }
                    var account = node.QuerySelector(".s-p .account");
                    if (account != null)
                        a.source += $"-{account.InnerText}";
                    a.state = ((int)EnumTypes.ArticleStatus.nonChecked);//未审核
                    a.date = DateTime.Now.ToString();
                    var copyRight = false;
                    a.content= GetArticleContent(a.htmlurl,out copyRight);
                    var comm = GetComment(a.htmlurl);
                    if (comm != null)
                    {
                        a.ReadNum = comm.read_num;
                        a.LikeNum = comm.like_num;
                    }
                    if (!copyRight)
                        result.Add(a);
                }
                var m = doc.QuerySelector("div .mun")?.InnerText.Remove(0, 3);
                m = m?.Substring(0, m.IndexOf("条", StringComparison.OrdinalIgnoreCase)).Replace(",","");
                var maxRecord = 1;
                var maxPage = 1;
                if (int.TryParse(m, out maxRecord))
                {
                    if (maxRecord > 100) maxPage = 10;
                    else
                        maxPage = maxRecord / 10 + 1;
                }
                if (page < maxPage)
                    result.AddRange(GetArticleListKey(key, tagid, tagname, page + 1));

            }
            catch (Exception e)
            {
                Trace.TraceError(e.Message);
                throw;
            }

            return result;
        }
        /// <summary>
        /// 根据正则表达式获取第一个匹配的结果
        /// </summary>
        /// <param name="pattern"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        private static string RegexFetch(string pattern, string input)
        {
            var g = new Regex(pattern);
            return !g.IsMatch(input) ? string.Empty : g.Matches(input)[0].Value;
        }
        private string GetArticleContent(string requestUrl,out bool copyright)
        {
            try
            {
                WebRequestHelper.Referer = requestUrl;
                WebRequestHelper.Host = "mp.weixin.qq.com";
                var htmlResult = WebRequestHelper.Request(requestUrl);
                var reg = new Regex("js_content([\\s\\S]+?)</div>");
                var copy = new Regex("id=\"copyright_logo\"");
                var copyMath = copy.Match(htmlResult);
                copyright = copyMath.Success;
                var match = reg.Match(htmlResult);
                if (match.Success)
                {
                    var result = match.Value.Substring(13);
                    result = result.Substring(0, result.Length - 6);
                    result = result.Replace("data-src", "src");
                    var eva = new MatchEvaluator(WordScrambler);
                    result = Regex.Replace(result, "<img[^<>]*?\\ssrc=['\"]?(.*?)['\"].*?>", eva);
                    var eva2 = new MatchEvaluator(WordScramblerBackground);
                    result = Regex.Replace(result, "background-image:\\s*url\\([^\\s]*\\)", eva2);
                    return result;
                }
            }
            catch (Exception e)
            {
                Trace.WriteLine(e.Message);
                Trace.WriteLine(e.StackTrace);
                copyright = false;
                return string.Empty;
            }
            
            
            return string.Empty;
        }
        /// <summary>
        /// 通过文章的链接，解析文章的内容
        /// </summary>
        /// <param name="url">文章的链接地址</param>
        /// <returns></returns>
        private MArticle SearchArticle(string url,int tagid,string tagname)
        {
            var ma = new MArticle();
            ma.Tag_Id = tagid;
            ma.Tag_Name = tagname;
            ma.htmlurl = url;
            ma.sourceid = (int)EnumTypes.SourceIds.WeiChat;
            ma.source = EnumTypes.GetEnumDesc(typeof(EnumTypes.SourceIds), ma.sourceid);
            ma.source += "-手动贴链接";
            ma.state = ((int)EnumTypes.ArticleStatus.nonChecked);//未审核
            ma.date = DateTime.Now.ToString();
            var www = new HttpFire(url) { Method = HttpRequestMethod.Get };
            var htmlResult = www.GetString();
            
            var regtitle=new Regex("(msg_title = )+(.)*\"");
            var matchtitle = regtitle.Match(htmlResult).Value;
            ma.title = matchtitle.Substring(13).TrimEnd('"');
            ma.title = HttpUtility.HtmlDecode(ma.title);
            var reglogo=new Regex("(msg_cdn_url = )+(.)*\"");
            var matchlogo = reglogo.Match(htmlResult).Value;
            ma.logo = matchlogo.Substring(15).TrimEnd('"');
            var regtime = new Regex("(publish_time = )+(.)*\"");
            var matchtime = regtime.Match(htmlResult).Value;
            ma.html_date = matchtime.Substring(16).Replace("\" || \"\"", "");
            var reg = new Regex("js_content([\\s\\S]+?)</div>");
            var match = reg.Match(htmlResult);
            if (!match.Success) return null;
            var result = match.Value.Substring(13);
            result = result.Substring(0, result.Length - 6);
            result = result.Replace("data-src", "src");
            var eva = new MatchEvaluator(WordScrambler);
            result = Regex.Replace(result, "<img[^<>]*?\\ssrc=['\"]?(.*?)['\"].*?>", eva);
            var eva2 = new MatchEvaluator(WordScramblerBackground);
            result = Regex.Replace(result, "background-image:\\s*url\\([^\\s]*\\)", eva2);
            ma.content = result;
            var comm = GetComment(url);
            if (comm != null)
            {
                ma.ReadNum = comm.read_num;
                ma.LikeNum = comm.like_num;
            }
            return ma;
        }
        private static string WordScramblerBackground(Match match)
        {
            string img = match.Value;
            bool flag = img.IndexOf("base64", StringComparison.OrdinalIgnoreCase) > 0;
            string result;
            if (flag)
            {
                result = img;
            }
            else
            {
                string url = img.Substring(img.IndexOf("&quot;", StringComparison.OrdinalIgnoreCase) + 6);
                try
                {
                    string realUrl = ConfigurationManager.AppSettings["proxyimg"] + url;
                    result = (string.IsNullOrEmpty(url) ? img : img.Replace(url, realUrl));
                }
                catch (Exception e)
                {
                    Trace.TraceError(e.Message);
                    throw;
                }
            }
            return result;
        }
        private string WordScrambler(Match match)
        {
            var url = match.Groups[1].Value;
            var img = match.Value;
            var realUrl = ConfigurationManager.AppSettings["proxyimg"] + url;
            return string.IsNullOrEmpty(url) ? string.Empty : img.Replace(url, realUrl);
        }

        /// <summary>
        /// 根据链接获取评论
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private SougouWeiChatCommentModel GetComment(string link)
        {
            Uri url;
            try
            {
                if (Uri.TryCreate(link, UriKind.RelativeOrAbsolute, out url))
                {
                    var query = url.Query;
                    var curl = "https://mp.weixin.qq.com/mp/getcomment" + query;
                    var htmlResult = WebRequestHelper.Request(curl);
                    var model = JsonConvert.DeserializeObject<SougouWeiChatCommentModel>(htmlResult);
                    return model;
                }
            }
            catch
            {
                return null;
            }
            
            return null;

        }

        private void frmSheHui_FormClosed(object sender, FormClosedEventArgs e)
        {
            thdOne.Abort();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            Do(txtTagName.Text);
        }

        private void btnKeyWord_Click(object sender, EventArgs e)
        {
            Do(txtTagName.Text,1);
        }

        private void btnLink_Click(object sender, EventArgs e)
        {
            Do(txtTagName.Text, 2,txtLink.Text);
        }
    }
}